package com.example.demo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.model.Order;
import com.example.demo.model.User;
import com.example.demo.service.OrderService;

@Controller
@RequestMapping("/order")
public class OrderController {
	
	@Autowired
	private OrderService orderService;

	@GetMapping("list")
	@ResponseBody
	public Object list(HttpServletRequest request) {
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("code", 20000);
		try {
			Map<String,Object> user = (Map)request.getSession().getAttribute("user");
			String username = user.get("username").toString();
			Order queryOrder = new Order();
			queryOrder.setUsername(username);
			ExampleMatcher matcher = ExampleMatcher.matching()
				.withMatcher("username", ExampleMatcher.GenericPropertyMatchers.ignoreCase());
			Example<Order> example = Example.of(queryOrder, matcher);
			
			List<Order> findAll = orderService.findAll(example);
			
			result.put("message", findAll);
		} catch (Exception e) {
			result.put("code", 1);
			result.put("message", "请求失败"+e.getMessage());
		}
		return result;
	}
	
	@PostMapping("saveOrUpdate")
	@ResponseBody
	public Object saveOrUpdate(Order entity) {
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("code", 20000);
		try {
			orderService.saveOrUpdate(entity);
		} catch (Exception e) {
			result.put("code", 1);
			result.put("message", "请求失败，"+e.getMessage());
		}
		return result;
	}
	@GetMapping("info")
	@ResponseBody
	public Object info(String orderId) {
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("code", 20000);
		try {
			Optional<Order> ptionalResult = orderService.findById(orderId);
			Order order = ptionalResult.get();
			result.put("message", order);
		} catch (Exception e) {
			result.put("code", 1);
			result.put("message", "请求失败，"+e.getMessage());
		}
		return result;
	}
	
}
